<template>
  <a-select
    :placeholder="placeholder || $t('m.common.label.option_select')"
    v-model="selectValue"
    :allowClear="allowClear"
    :options="selectOptions"
    :disabled="disabled"
    @change="onChange"
  />
</template>

<script>

  import {getAction} from "@/api/manage";
  import YchConstant from "@/api/YchConstant";

  export default {
    name: 'SelectDs',
    props: {
      value: {
        type: String,
        default: null
      },
      placeholder: {
        type: String,
      },
      disabled: {
        type: Boolean,
        default: false
      },
      allowClear: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        selectValue: undefined,
        selectOptions: [],
        url: {
          getAllDs: YchConstant.PREFIX_SYSTEM + "/sysDatasourceConfig/getAllDs",
        }
      }
    },
    watch: {
      value: {
        handler(val) {
          this.selectValue = val || undefined;
        },
        immediate: true
      }
    },
    methods: {
      onChange(value) {
        this.$emit('input', value)
        this.$emit('change', value)
      }
    },
    created() {
      getAction(this.url.getAllDs, {}).then((res) => {
        if (res.success) {
          res.result.forEach(vo => {
            const newVo = {
              value: vo.datasourceKey,
              label: vo.datasourceName
            };
            this.selectOptions.push(newVo);
          });
        } else {
          this.messageUtil.warning(res.message);
        }
      }).finally(() => {
      });
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>
